package com.zcyh.exam.job.quartz.config.quartz;


import cn.hutool.core.util.StrUtil;
import com.zcyh.exam.mapper.QuartzMapper;
import com.zcyh.exam.model.entity.QuartzInfo;
import com.zcyh.exam.utils.spring.SpringUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.StringUtils;

import java.util.Map;


/**
 * CAUTION:初步功能
 * 实现Job，JobDataMap中serviceTag必须和spring中所注册的BeanId相同
 * 否则Job不会被执行
 * @author
 * @version 1.0
 */
public class QuartzJobBean implements Job{
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException{
        String targetBeanId = (String) context.getMergedJobDataMap().get("serviceTag");
        if (StringUtils.isEmpty(targetBeanId)){
            return;
        }
        Object targetBean= SpringUtil.getBean(targetBeanId);
        if (null == targetBean){
            return;
        }
        if (!(targetBean instanceof QuartzJob)){
            return;
        }
        Map<?, ?> args = (Map<?, ?>) context.getMergedJobDataMap().get("args");
        QuartzJob job = (QuartzJob) targetBean;

        try{
            job.execute(args);

            String uuid = (String) args.get("uuid");
            if(StrUtil.isNotBlank(uuid)){
                QuartzMapper mapper = SpringUtil.getBean(QuartzMapper.class);
                QuartzInfo quartzInfo = mapper.selectById(uuid);
                quartzInfo.setExecStatus("1");
                mapper.updateById(quartzInfo);
                if(StrUtil.isNotBlank(quartzInfo.getJobId())){
                    QuartzTaskScheduler scheduler = SpringUtil.getBean(QuartzTaskScheduler.class);
                    scheduler.terminateJob(quartzInfo.getJobId());
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
